﻿using Abp.Collections.Extensions;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Runtime.Validation.Interception;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace ARchGL.Platform.Web.Validation
{
    public class AbpActionInvocationValidator : MethodInvocationValidator
    {
        private bool _isValidatedBefore;

        public AbpActionInvocationValidator(IValidationConfiguration configuration, IIocResolver iocResolver)
            : base(configuration, iocResolver)
        {
        }

        protected ActionExecutingContext ActionContext { get; private set; }

        public void Initialize(ActionExecutingContext actionContext, MethodInfo methodInfo)
        {
            base.Initialize(
                methodInfo,
                GetParameterValues(actionContext, methodInfo)
            );

            ActionContext = actionContext;
        }

        protected virtual object[] GetParameterValues(ActionExecutingContext actionContext, MethodInfo methodInfo)
        {
            var parameters = methodInfo.GetParameters();
            var parameterValues = new object[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                parameterValues[i] = actionContext.ActionDescriptor.Parameters[i];
            }

            return parameterValues;
        }

        protected override void SetValidationErrors(object validatingObject)
        {
            base.SetValidationErrors(validatingObject);
        }

        protected override void ThrowValidationError()
        {
            base.ThrowValidationError();
        }

        protected override void ValidateObjectRecursively(object validatingObject, int currentDepth)
        {
            base.ValidateObjectRecursively(validatingObject, currentDepth);
        }
    }
}